<template>
  <div class="task-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>任务列表</span>
          <el-button type="primary" @click="openCreateTaskModal" style="float: right;">创建任务</el-button>
        </div>
      </template>
      <el-table :data="tasks" style="width: 100%">
        <el-table-column prop="name" label="任务名称"></el-table-column>
        <el-table-column prop="status" label="状态" :formatter="statusFormatter"></el-table-column>
        <el-table-column prop="createTime" label="创建时间"></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
            <el-button type="success" size="small" @click="handleStart(scope.row.id)" :disabled="scope.row.status !== 0 && scope.row.status !== 3 && scope.row.status !== 4 && scope.row.status !== 5">启动</el-button>
            <el-button type="primary" size="small" @click="handleViewSteps(scope.row.id)">查看步骤</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
          style="margin-top: 20px;"
      ></el-pagination>
    </el-card>

    <el-dialog title="创建任务" v-model="createTaskModalVisible">
      <el-form :model="newTask" label-width="80px">
        <el-form-item label="任务名称">
          <el-input v-model="newTask.name"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input type="textarea" v-model="newTask.description"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createTaskModalVisible = false">取 消</el-button>
          <el-button type="primary" @click="createTask">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog title="编辑任务" v-model="editTaskModalVisible">
      <el-form :model="currentTask" label-width="80px">
        <el-form-item label="任务名称">
          <el-input v-model="currentTask.name"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input type="textarea" v-model="currentTask.description"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editTaskModalVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateTask">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'TaskList',
  data() {
    return {
      tasks: [],
      total: 0,
      pageSize: 10,
      currentPage: 1,
      createTaskModalVisible: false,
      editTaskModalVisible: false,
      newTask: {
        name: '',
        description: ''
      },
      currentTask: {
        id: null,
        name: '',
        description: ''
      }
    };
  },
  mounted() {
    this.fetchTasks();
  },
  methods: {
    fetchTasks() {
      axios.get('/api/task', {
        params: {
          page: this.currentPage,
          size: this.pageSize
        },
        headers: {
          'Authorization': 'Bearer ' + localStorage.getItem('token')
        }
      })
      .then(response => {
        this.tasks = response.data.records;
        this.total = response.data.total;
      })
      .catch(error => {
        console.error('Error fetching tasks:', error);
      });
    },
    handlePageChange(val) {
      this.currentPage = val;
      this.fetchTasks();
    },
    openCreateTaskModal() {
      this.newTask = {
        name: '',
        description: ''
      };
      this.createTaskModalVisible = true;
    },
    createTask() {
      axios.post('/api/task', this.newTask, {
        headers: {
          'Authorization': 'Bearer ' + localStorage.getItem('token')
        }
      })
      .then(response => {
        this.createTaskModalVisible = false;
        this.fetchTasks();
      })
      .catch(error => {
        console.error('Error creating task:', error);
      });
    },
    handleEdit(task) {
      this.currentTask = { ...task };
      this.editTaskModalVisible = true;
    },
    updateTask() {
      axios.put(`/api/task/${this.currentTask.id}`, this.currentTask, {
        headers: {
          'Authorization': 'Bearer ' + localStorage.getItem('token')
        }
      })
      .then(response => {
        this.editTaskModalVisible = false;
        this.fetchTasks();
      })
      .catch(error => {
        console.error('Error updating task:', error);
      });
    },
    handleDelete(id) {
      this.$confirm('此操作将永久删除该任务, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete(`/api/task/${id}`, {
          headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('token')
          }
        })
        .then(response => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.fetchTasks();
        })
        .catch(error => {
          console.error('Error deleting task:', error);
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleStart(id) {
      axios.post(`/api/task/${id}/start`, {}, {
        headers: {
          'Authorization': 'Bearer ' + localStorage.getItem('token')
        }
      })
      .then(response => {
        this.$message({
          type: 'success',
          message: '任务已启动!'
        });
        this.fetchTasks();
      })
      .catch(error => {
        console.error('Error starting task:', error);
      });
    },
    handleViewSteps(id) {
      this.$router.push(`/task/${id}/steps`);
    },
    statusFormatter(row) {
      switch (row.status) {
        case 0:
          return '待执行';
        case 1:
          return '执行中';
        case 2:
          return '已完成';
        case 3:
          return '失败';
        case 4:
          return '已停止';
        case 5:
          return '已暂停';
        default:
          return '未知状态';
      }
    }
  }
};
</script>

<style scoped>
.task-list {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style> 